import { useState, useEffect } from "react";

interface DefaultResultData {
  total: number;
  data: any[];
}
interface IOptions {
  currentLabel?: string; // 当前页自定义label
  sizeLabel?: string; // 条数自定义label
  defaultCurrent?: number;
  defaultSize?: number;
  apiRun: (params: any) => Promise<DefaultResultData>;
  formatData?: (res: any) => Promise<DefaultResultData>;
}
interface IReturn {
  pagination: object;
  dataSource: any[];
  getData: Function;
  [key: string]: any;
}
const usePagination = ({
  currentLabel = "current",
  sizeLabel = "size",
  apiRun,
  formatData,
  defaultCurrent,
  defaultSize,
}: IOptions): IReturn => {
  const [current, setCurrent] = useState<number>(1);
  const [size, setSize] = useState<number>(10);
  const [total, setTotal] = useState<number>(0);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);

  // 获取数据源
  const getData = async <Search>(
    search?: Search
  ): Promise<[string | null, any] | undefined> => {
    setLoading(true);
    const params = { [currentLabel]: current, [sizeLabel]: size };
    const res = await apiRun({ ...params, ...search });
    setLoading(false);

    const data = formatData
      ? await formatData(res)
      : (res as DefaultResultData);
    if (Object.prototype.toString.call(data.total) !== "[object Number]") {
      return Promise.reject("total is required number");
    }
    setDataSource(data.data);
    setTotal(data.total);
  };
  const onChange = (page: number, PageSize: number) => {
    // console.log(page, PageSize);
    setCurrent(page);
    setSize(PageSize);
  };
  useEffect(() => {
    try {
      getData();
    } catch (e) {
      console.error(e);
    }
  }, [current, size]);
  useEffect(() => {
    defaultCurrent && setCurrent(defaultCurrent);
  }, [defaultCurrent]);
  useEffect(() => {
    defaultSize && setSize(defaultSize);
  }, [defaultSize]);
  return {
    pagination: {
      [currentLabel]: current,
      [sizeLabel]: size,
      total,
      onChange,
    },
    dataSource,
    getData,
    loading,
  };
};

export default usePagination;
